package com.gz.purchase.fragment;


import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.purchase.R;
import com.gz.purchase.adapter.MainProductsAdapter;
import com.gz.purchase.app.Define;
import com.gz.purchase.app.SubmitOrderActivity;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IOrder;
import com.gz.purchase.library.IProduct;
import com.gz.purchase.library.listener.GetMainProductsListener;
import com.gz.purchase.library.listener.RequestCode;
import com.gz.purchase.library.pojo.ProductInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.FooterView;
import com.gz.purchase.widget.LoadingCover;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.w3c.dom.Text;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class MainFragment extends Fragment implements LoadingCover.OnLoadingCoverRefreshListener,
        View.OnClickListener, PullToRefreshBase.OnRefreshListener, FooterView.OnFooterViewRefreshListener {
    private View mConvertView;
    private Context mContext;
    private Button bt_buy;
    private PullToRefreshListView mPullListView;
    private LoadingCover mloadingCover;
    private FooterView mFooterView;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private UserInfo info;
    private List<ProductInfo> mDataList;
    private MainProductsAdapter mAdapter;
    private MyGetMainProductsListener mPullRequestlistener;
    private MyGetMainProductsListener mScrollRequestListener;
    private int page = 1;
    private RefreshReceiver mRefreshReceiver;
    private boolean isReceiveBrocast = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 在订单提交页面，如果提交订单成功，则给首页发送一个广播，让其刷新界面，且不保留之前商品的选中状态，我选择的个数！！
        mRefreshReceiver = new RefreshReceiver();
        IntentFilter filter = new IntentFilter(Define.ACTION_REFRESH_HOME);
        getActivity().registerReceiver(mRefreshReceiver, filter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null) {
            mConvertView = inflater.inflate(R.layout.fragment_main, container, false);
            initView(inflater);
        }
        initListener();
        initData();
        return mConvertView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((ViewGroup) mConvertView.getParent()).removeView(mConvertView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPullRequestlistener.release();
        mScrollRequestListener.release();
        getActivity().unregisterReceiver(mRefreshReceiver);
    }

    @Override
    public void onLoadingCoverRefresh() {
        page = 1;
        IProduct.getInstance().getHomeProducts(page, null, mPullRequestlistener);
    }

    @Override
    public void onFooterViewRefresh() {
        page++;
        IProduct.getInstance().getHomeProducts(page, null, mScrollRequestListener);

    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        page = 1;
        IProduct.getInstance().getHomeProducts(page, null, mPullRequestlistener);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.bt_buy) {
            if (mDataList.size() == 0) {
                ToastUtils.showToast(mContext, "暂无数据");
                return;
            }

            List<ProductInfo> selectedProducts = new ArrayList<ProductInfo>();
            for (ProductInfo info : mDataList) {
                if (info.isSelected()) {
                    selectedProducts.add(info);
                }
            }

            if (selectedProducts.size() == 0) {
                ToastUtils.showToast(mContext, "请选择商品");
                return;
            } else {
                Intent intent = new Intent();
                intent.setClass(mContext, SubmitOrderActivity.class);
                intent.putExtra("selectedProducts", (Serializable) selectedProducts);
                startActivity(intent);

            }
        }

    }


    public void initView(LayoutInflater inflater) {
        mContext = getActivity();
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        tv_actionbar_title = (TextView) mConvertView.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) mConvertView.findViewById(R.id.tv_actionbar_deliveryName);
        bt_buy = (Button) mConvertView.findViewById(R.id.bt_buy);
        mPullListView = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
        mloadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
        mFooterView = (FooterView) inflater.inflate(R.layout.footer_view, null);
        mPullListView.getRefreshableView().addFooterView(mFooterView);
    }

    public void initListener() {
        mloadingCover.setOnLoadingCoverRefreshListener(this);
        mPullRequestlistener = new MyGetMainProductsListener(RequestCode.PULL, this);
        mScrollRequestListener = new MyGetMainProductsListener(RequestCode.SCROLL, this);
        bt_buy.setOnClickListener(this);
        mFooterView.setOnFooterViewRefreshListener(this);
        mPullListView.setOnScrollListener(mFooterView);
        mPullListView.setOnRefreshListener(this);
    }

    public void initData() {
        tv_actionbar_title.setText("主页");
        tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        mDataList = new ArrayList<ProductInfo>();
        mAdapter = new MainProductsAdapter(mDataList, mContext);
        mPullListView.setAdapter(mAdapter);
        onLoadingCoverRefresh();
    }


    private class  MyGetMainProductsListener extends GetMainProductsListener {
        private MainFragment mOuter;

        public MyGetMainProductsListener(RequestCode requestCode, MainFragment mOuter) {
            super(requestCode);
            this.mOuter = mOuter;
        }

        public void release() {
            new WeakReference<MainFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<ProductInfo> products) {
            if (products == null) {
                products = new ArrayList<ProductInfo>();
            }
            if (getRequestCode() == RequestCode.PULL) {
                // 如果这次刷新不是因为收到订单页面发来的广播，则要保留刷新之前的选中状态
                if (!mOuter.isReceiveBrocast) {
                    for (ProductInfo oldInfo : mOuter.mDataList) {
                        for (ProductInfo newInfo : products) {
                            // 刷新之后，如果这个商品之前没选中则不保留状态，如果刷新之后，这个商品剩余数==0 不保留状态
                            if (oldInfo.getProduct_id() == newInfo.getProduct_id() && oldInfo.isSelected() && newInfo.getProduct_num() > 0) {
                                newInfo.setSelectNum(oldInfo.getSelectNum());
                                newInfo.setIsSelected(oldInfo.isSelected());
                                continue;
                            }
                        }

                    }
                } else {
                    //如果是因为收到广播而刷新界面的，则不把刷新之前的选中状态保留，且把 isReceiveBrocast 置为false
                    mOuter.isReceiveBrocast = false;
                }
                mOuter.mDataList.clear();
            }
            mOuter.mDataList.addAll(products);
            mOuter.mAdapter.notifyDataSetChanged();

            if (products.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPullListView.setOnScrollListener(null);
            } else {
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPullListView.setOnScrollListener(mOuter.mFooterView);
            }

            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }

            mOuter.mloadingCover.onRefreshSuccess();

        }

        //存在未被关联的基础商品，请联系相关人员维护
        @Override
        public void onDataError(String shopname) {
            mOuter.mloadingCover.onRefreshFailed(Define.MSG_ON_DATA_ERROR);
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullListView.setOnScrollListener(null);
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (getRequestCode() == RequestCode.PULL) {

                createDialog(shopname);
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                ToastUtils.showToast(mOuter.getActivity(), Define.MSG_ON_DATA_ERROR);
            }


        }

        //暂无库存
        @Override
        public void onNoMoreData() {
            mOuter.mloadingCover.onRefreshFailed(Define.MSG_NOTHING);
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullListView.setOnScrollListener(null);

            if (getRequestCode() == RequestCode.PULL) {
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                ToastUtils.showToast(mOuter.getActivity(), "暂无内容");
            }
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }


        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (getRequestCode() == RequestCode.SCROLL) {
                mOuter.page--;
            }
            mOuter.mFooterView.onRefreshFailed();
            mOuter.mloadingCover.onRefreshFailed(Define.MSG_LOADING_BY_CLICK);
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mloadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (getRequestCode() == RequestCode.SCROLL) {
                mOuter.page--;
            }
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_ON_RESPONSE_FAILED);
        }
    }

    private class RefreshReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            isReceiveBrocast = intent.getBooleanExtra("isReceiveBrocast", true);
            onLoadingCoverRefresh();
        }
    }

    private void createDialog(String shopname){

        final AlertDialog dialog=new AlertDialog.Builder(getActivity()).create();
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_dialog, null);
        dialog.setView(view, 0, 0, 0, 0);
        dialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 650;
        params.height = 800;
        dialog.getWindow().setAttributes(params);
        TextView textview = (TextView) view.findViewById(R.id.textview);
        textview.setText(shopname);
        TextView btn_ok=(TextView) view.findViewById(R.id.btn_confirm);
        btn_ok.setOnClickListener(new View.OnClickListener() {//点击取消按钮

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();

            }
        });
    }

}
